<?php

defined('IN_IA') or exit('Access Denied');
//载入日志函数
load()->func('logging');

//include "model.php";
class Laoyou_csyxModuleSite extends WeModuleSite {

    public $tablename = 'laoyou_csyx_reply';
    public $tablefans = 'laoyou_csyx_fans';
    public $tablerecord = 'laoyou_csyx_record';
    public $tableshare = 'laoyou_csyx_share';
    public $tablewinning = 'laoyou_csyx_winning';
    public $tabletx = 'laoyou_csyx_tx';

    public function getItemTiles() {
        global $_W;
        $articles = pdo_fetchall("SELECT id,rid, title FROM " . tablename($this->tablename) . " WHERE weid = '{$_W['uniacid']}'");
        if (!empty($articles)) {
            foreach ($articles as $row) {
                $urls[] = array('title' => $row['title'], 'url' => $this->createMobileUrl('index', array('id' => $row['rid'])));
            }
            return $urls;
        }
    }

    public function doMobileindex() {
        global $_GPC, $_W;
        //检查是否微信游览器    
        $this->checkIsWebchat();
        
        $id = intval($_GPC['id']);
        $reply = pdo_fetch("SELECT * FROM " . tablename($this->tablename) . "WHERE rid = " . $id);
        if (!$_W['fans']['follow']) {
            $url = $reply['subscribeurl'] ? $reply['subscribeurl'] : $_W['account']['subscribeurl'];

            header("location:" . $url);
            //message('请先关注该公众号',$url,'error');
        }

        $today = date("Ymd", time());
        $from_user = $_W['fans']['from_user'];
        //$from_user = 'o9xMHjwMeIwgAZjydqqssm_JC3Ss';
        if (!$from_user) {
            message('获取用户ID失败，请使用微信打开此链接。', '', 'error');
        }

        $sharelink = $_W['siteroot'] . "app/" . urldecode($this->createMobileUrl('index', array('id' => $id, 'openid' => $from_user)));

        $starttime = date('Ymd', $reply['starttime']);
        $endtime = date('Ymd', $reply['endtime']);

        if ($today < $starttime) {
            message('该活动尚未开始', '', 'error');
        }

        if ($today > $endtime) {
            message('该活动已过期', '', 'error');
        }

        $access_token = WeAccount::token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $from_user . "&lang=zh_CN";
        $get = ihttp_get($url);
        $info = json_decode($get['content'], true);
        $tx_info = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_tx') . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        if ($info['subscribe'] == 1) {
            $data_tx['rid'] = $id;
            $data_tx['weid'] = $_W['uniacid'];
            $data_tx['openid'] = $from_user;
            $data_tx['tx'] = $info['headimgurl'];
            $data_tx['nickname'] = $info['nickname'];
            if ($tx_info) {
                pdo_update($this->tabletx, array('tx' => $info['headimgurl'], 'nickname' => $info['nickname'], 'edittime' => time()), array('openid' => $from_user, 'rid' => $id));
            } else {
                $data_tx['addtime'] = time();
                pdo_insert($this->tabletx, $data_tx);
            }
        }

        $time = date('Ymd', time());
        $qc = $_W['account']['qrcode'];
        $rank = pdo_fetchall("SELECT * FROM " . tablename($this->tablerecord) . "WHERE rid = " . $id . " and abnormal=0 ORDER BY score DESC");
        $info_t2 = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_tx') . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        $tx = $info_t2['tx'];
        foreach ($rank as $k => $v) {
            $info_t = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_tx') . "WHERE rid = " . $id . " AND openid = '" . $v['openid'] . "'");
            $rank[$k]['nn'] = $info_t['nickname'];
            $rank[$k]['tx'] = $info_t['tx'];
        }
        $award = array(
            "one" => array("name" => $reply['c_name_one'], "type" => $reply['c_type_one'], "probalilty" => $reply['c_rate_one'], "total" => $reply['c_num_one'], "draw" => $reply['c_draw_one']),
            "two" => array("name" => $reply['c_name_two'], "type" => $reply['c_type_two'], "probalilty" => $reply['c_rate_two'], "total" => $reply['c_num_two'], "draw" => $reply['c_draw_two']),
            "three" => array("name" => $reply['c_name_three'], "type" => $reply['c_type_three'], "probalilty" => $reply['c_rate_three'], "total" => $reply['c_num_three'], "draw" => $reply['c_draw_three']),
            "four" => array("name" => $reply['c_name_four'], "type" => $reply['c_type_four'], "probalilty" => $reply['c_rate_four'], "total" => $reply['c_num_four'], "draw" => $reply['c_draw_four']),
            "five" => array("name" => $reply['c_name_five'], "type" => $reply['c_type_five'], "probalilty" => $reply['c_rate_five'], "total" => $reply['c_num_five'], "draw" => $reply['c_draw_five']),
            "six" => array("name" => $reply['c_name_six'], "type" => $reply['c_type_six'], "probalilty" => $reply['c_rate_six'], "total" => $reply['c_num_six'], "draw" => $reply['c_draw_six']),
        );
        $winning = pdo_fetchall("SELECT * FROM " . tablename($this->tablewinning) . "WHERE rid = " . $id . " AND from_user = '" . $from_user . "'");
        if ($winning) {
            $is_w = 1;
        } else {
            $is_w = 2;
        }



        $fans = pdo_fetchall("SELECT * FROM " . tablename($this->tablefans) . "WHERE rid = " . $id);

        $record = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_record') . " WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        if ($record) {
            $r_time = date('Ymd', $record['edittime']);
            if ($r_time != $today) {
                pdo_update($this->tablefans, array('num' => 0), array('openid' => $from_user, 'rid' => $id));
            }
        }

        $is_fans = pdo_fetch("SELECT * FROM " . tablename($this->tablefans) . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        if (!$is_fans && strlen($from_user) == 28) {
            $data['rid'] = intval($_GPC['id']);
            $data['weid'] = $_W['uniacid'];
            $data['openid'] = $from_user;
            $data['num'] = 0;
            $data['addtime'] = time();
            pdo_insert($this->tablefans, $data);
            $is_fans = pdo_fetch("SELECT * FROM " . tablename($this->tablefans) . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        }

        $fansnum = count($fans) + $reply['people_num'];

        if ($_GPC['openid']) {
            $to_user_share_num = pdo_fetchall("SELECT * FROM " . tablename($this->tableshare) . "WHERE to_user = '" . $from_user . "' AND addtime = " . $today . " AND rid = " . $id);

            $is_share = false;
            foreach ($to_user_share_num as $k => $v) {
                if ($v['from_user'] = $_GPC['openid']) {
                    $is_share = true;
                    break;
                }
            }

            if (!$is_share) {
                $fanss = pdo_fetch("SELECT * FROM " . tablename($this->tablefans) . "WHERE openid = '" . $_GPC['openid'] . "' AND rid=" . $id);
                $data_s['edittime'] = time();
                $data_s['num'] = $fanss['num'] + $reply['addnum'];
                pdo_update($this->tablefans, $data_s, array('openid' => $_GPC['openid'], 'rid' => $id));
                pdo_insert($this->tableshare, array('to_user' => $from_user, 'form_user' => $_GPC['openid'], 'addtime' => $today, 'rid' => $id, 'weid' => $_W['uniacid']));
            }
        }

        $appId = $_W['account']['key'];
        $appSecret = $_W['account']['secret'];
        require_once "jssdk.php";
        $jssdk = new JSSDK($appId, $appSecret);
        $signPackage = $jssdk->GetSignPackage();


        //$share = $_W['account']['jssdkconfig'];
        // if($chance && $time >= date('Ymd',$reply['starttime']) && $time <= date('Ymd',$reply['endtime'])){
        // include $this->template('index');
        // }
        // else if($chance == 0 || $time > date('Ymd',$reply['endtime']) || $time < date('Ymd',$reply['starttime'])){
        // include $this->template('over');
        // }
        include $this->template('index');
    }
    
    private function checkIsWebchat(){
        global $_W,$_GPC;
        if($_W['container']!='wechat'){
            die("<!DOCTYPE html>
				                <html>
				                    <head>
				                        <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
				                        <title>抱歉，出错了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
				                    </head>
				                    <body>
				                    <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><i class='icon80_smile'></i></span><div class='msg_content'><h4>请在微信客户端打开链接</h4></div></div></div>
				                    </body>
				                </html>");
        }
    }

    public function doMobilejoin() {
        header('content-type:application/html;charset=utf8');
        echo json_encode(array('isOutofJoinNum' => false));
    }

    public function doMobilebestrank() {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $from_user = $_W['fans']['from_user'];
        $record = pdo_fetchall("SELECT * FROM " . tablename('laoyou_csyx_record') . "WHERE rid = " . $id . " abnormal=0 ORDER BY score desc");
        foreach ($record as $k => $v) {
            if ($v['openid'] == $from_user) {
                $rank = $k + 1;
                $score = $v['score'];
                break;
            }
        }
        header('content-type:application/html;charset=utf8');
        echo json_encode(array('rank' => $rank, 'score' => $score));
    }

    public function doMobileseta() {
        global $_GPC, $_W;
        $today = date("Ymd", time());
        $from_user = $_W['fans']['from_user'];
        $id = intval($_GPC['id']);
        $score = $_GPC['score'];
        $fans = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_fans') . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        $is_fans = pdo_fetch("SELECT * FROM " . tablename($this->tablefans) . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        $reply = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_reply') . "WHERE rid = " . $id);
        $bestscore = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_record') . " WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        $record = pdo_fetchall("SELECT * FROM " . tablename('laoyou_csyx_record') . " WHERE rid = " . $id . " ORDER BY score desc");
        $r_time = date('Ymd', $bestscore['edittime']);

        //插入玩的日志
        pdo_insert('laoyou_csyx_play_log', array('rid' => $id, 'weid' => $_W['uniacid'], 'fans' => $fans['id'], 'score' => $score, 'addtime' => TIMESTAMP));
        if ($bestscore) {
            if ($score > $bestscore['score']) {
                pdo_update($this->tablerecord, array('score' => $score, 'edittime' => time()), array('openid' => $from_user, 'rid' => $id));
                $b_score = $score;
            } else {
                pdo_update($this->tablerecord, array('edittime' => time()), array('openid' => $from_user, 'rid' => $id));
                $b_score = $bestscore['score'];
            }
        } else {
            $data['rid'] = $id;
            $data['weid'] = $_W['uniacid'];
            $data['openid'] = $from_user;
            $data['score'] = $score;
            $data['edittime'] = time();
            pdo_insert($this->tablerecord, $data);
            $b_score = $score;
        }

        //异常
        $abnormalCustomer = pdo_fetch("select * from " . tablename("laoyou_csyx_abnormal_customer") . " where openid='{$from_user}' and weid={$_W['uniacid']} and rid={$id}");
        if ($reply['abnormal'] > 0 && $score > $reply['abnormal']) {
            
            //仅记录异常
            if ($reply['abnormal_manage'] == 0 ) {
                if (empty($abnormalCustomer)) {
                    pdo_insert('laoyou_csyx_abnormal_customer', array('openid' => $from_user, 'first_time' => TIMESTAMP, 'weid' => $_W['uniacid'], 'rid' => $id));
                } else {
                    pdo_update('laoyou_csyx_abnormal_customer', array('last_time' => TIMESTAMP), array('openid' => $from_user, 'weid' => $_W['uniacid'], 'rid' => $id));
                }
            }
            
            
            //禁止该条记录
            if ($reply['abnormal_manage'] == 1) {
                if ($score > $bestscore['score']) {
                    pdo_update($this->tablerecord, array('abnormal' => 1), array('openid' => $from_user, 'rid' => $id, 'weid' => $_W['uniacid']));
                }
                //不存在该用户的异常记录
                if (empty($abnormalCustomer)) {
                    pdo_insert('laoyou_csyx_abnormal_customer', array('openid' => $from_user, 'first_time' => TIMESTAMP, 'weid' => $_W['uniacid'], 'rid' => $id));
                } else {
                    pdo_update('laoyou_csyx_abnormal_customer', array('last_time' => TIMESTAMP), array('openid' => $from_user, 'weid' => $_W['uniacid'], 'rid' => $id));
                }
            }

            //封杀用户
            if ($reply['abnormal_manage'] == 2) {
                if ($score > $bestscore['score']) {
                    pdo_update($this->tablerecord, array('abnormal' => 1), array('openid' => $from_user, 'rid' => $id, 'weid' => $_W['uniacid']));
                }
                //不存在该用户的异常记录
                if (empty($abnormalCustomer)) {
                    pdo_insert('laoyou_csyx_abnormal_customer', array('ban' => 1, 'openid' => $from_user, 'first_time' => TIMESTAMP, 'weid' => $_W['uniacid'], 'rid' => $id));
                } else {
                    pdo_update('laoyou_csyx_abnormal_customer', array('ban' => 1, 'last_time' => TIMESTAMP), array('openid' => $from_user, 'weid' => $_W['uniacid'], 'rid' => $id));
                }
                //首次被系统自动封杀的用户
                $cheat=true;
            }
        }
        
        //已经被封杀的用户
        if($abnormalCustomer['ban']==1){
            $cheat=true;
        }

        //如果今天没玩过，加上今天的抽奖次数。
        if ($r_time != $today) {
            pdo_update($this->tablefans, array('num' => $fans['num'] + $reply['wnum'], 'edittime' => time()), array('openid' => $from_user, 'rid' => $id));
        }

        if (!$record) {
            $rank = 1;
        } else {
            $records = pdo_fetchall("SELECT * FROM " . tablename('laoyou_csyx_record') . " WHERE rid = " . $id . " ORDER BY score desc");
            foreach ($records as $k => $v) {
                if ($v['openid'] == $from_user) {
                    $rank = $k + 1;
                    break;
                }
            }
        }

        if ($score >= $reply['score']) {
            $rt = 0;
            $msg = '闯关成功！';
            $isSuc = true;
        } else {
            $rt = 1;
            $msg = '闯关失败！';
            $isSuc = false;
        }

        $fansss = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_fans') . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");

        echo json_encode(array('isSuc' => $isSuc, 'achieve' => intval($b_score), 'rank' => $rank, 'minScore' => $reply['score'], 'rt' => $rt, 'msg' => $msg, 'count' => $fansss['num'],'cheat'=>$cheat));
    }

    private function cal_prize($arr, $max) {
        $rand = rand(1, $max);

        $tmp = 0;
        if (is_array($arr)) {
            foreach ($arr as $key => $value) {
                $tmp += $value;
                if ($rand <= $tmp) {
                    return $key;
                }
            }
        }

        return null;
    }

    public function doMobileresult() {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $time = date('Ymd', time());
        $from_user = $_W['fans']['from_user'];
        //$from_user = 'oigVZuNcQXO60N0jnLAw9qRvcuIE';
        $reply = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_reply') . "WHERE rid = " . $id);
        $addnum = $reply['addnum'];
        $fans = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_fans') . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");




        if ($fans['num'] > 0) {
            pdo_update($this->tablefans, array('num' => $fans['num'] - 1), array('openid' => $from_user));
        }

        //被封杀的用户永远不可能中奖!!!!!!!!!!!!!!!!
        $abnormalCustomer = pdo_fetch("select * from " . tablename("laoyou_csyx_abnormal_customer") . " where openid='{$from_user}' and weid={$_W['uniacid']} and rid={$id}");
        if (!empty($abnormalCustomer) && $abnormalCustomer['ban'] == 1) {
            pdo_insert('laoyou_csyx_shake_log', array('rid' => $id, 'weid' => $_W['uniacid'], 'fans' => $fans['id'], 'winid' => 0, 'addtime' => TIMESTAMP));
            echo '{"rt":999,"success":false,"awardStyle":null,"awardName":null,"awardCode":null}';
            exit;
        }

        //计算每个礼物的概率
        $gifts = array(
            "one" => array("name" => $reply['c_name_one'], "type" => $reply['c_type_one'], "probalilty" => $reply['c_rate_one'], "total" => $reply['c_num_one'], "draw" => $reply['c_draw_one']),
            "two" => array("name" => $reply['c_name_two'], "type" => $reply['c_type_two'], "probalilty" => $reply['c_rate_two'], "total" => $reply['c_num_two'], "draw" => $reply['c_draw_two']),
            "three" => array("name" => $reply['c_name_three'], "type" => $reply['c_type_three'], "probalilty" => $reply['c_rate_three'], "total" => $reply['c_num_three'], "draw" => $reply['c_draw_three']),
            "four" => array("name" => $reply['c_name_four'], "type" => $reply['c_type_four'], "probalilty" => $reply['c_rate_four'], "total" => $reply['c_num_four'], "draw" => $reply['c_draw_four']),
            "five" => array("name" => $reply['c_name_five'], "type" => $reply['c_type_five'], "probalilty" => $reply['c_rate_five'], "total" => $reply['c_num_five'], "draw" => $reply['c_draw_five']),
            "six" => array("name" => $reply['c_name_six'], "type" => $reply['c_type_six'], "probalilty" => $reply['c_rate_six'], "total" => $reply['c_num_six'], "draw" => $reply['c_draw_six']),
        );

        //计算每个礼物的概率
        $probability = 0;
        $rate = 1;
        $award = array();
        $awards = array(); //奖品名字 (同时可中多个奖品，然后随机派奖)
        //找到最长小数
        $max_len = 0;
        foreach ($gifts as $name => $gift) {
            $temp = explode('.', $gift['probalilty']);
            $temp = $temp[1];
            $temp_len = strlen($temp);
            $max_len = $max_len < $temp_len ? $temp_len : $max_len;
        }

        $rate = pow(10, $max_len);

        foreach ($gifts as $name => $gift) {
            if ($gift['total'] - $gift['draw'] <= 0) {
                continue;
            }
            if (empty($gift['probalilty'])) {
                continue;
            }

            $award[] = array('prizetype' => $name, 'name' => $gift['name'], 'probalilty' => $gift['probalilty'] * $rate, 'total' => $gift['total'], 'type' => $gift['type']);
            $arr_pro[] = intval($gift['probalilty'] * $rate);
        }

        $result = (!empty($arr_pro)) ? $this->cal_prize($arr_pro, $rate * 100) : null;

        $res = $award[$result]; //中奖项

        $prizetype = $res['prizetype'];
        if ($prizetype == 'one') {
            $k = 1;
            $typename = '一等奖';
        }if ($prizetype == 'two') {
            $k = 2;
            $typename = '二等奖';
        }if ($prizetype == 'three') {
            $k = 3;
            $typename = '三等奖';
        }if ($prizetype == 'four') {
            $k = 4;
            $typename = '四等奖';
        }if ($prizetype == 'five') {
            $k = 5;
            $typename = '五等奖';
        }if ($prizetype == 'six') {
            $k = 6;
            $typename = '六等奖';
        }

        $win = pdo_fetchall("SELECT * FROM " . tablename($this->tablewinning) . " WHERE from_user = '" . $from_user . "' AND rid = " . $id);
        $pirzenum = count($win);
        $winid = 0;
        if ($res && $fans['num'] > 0 && $pirzenum < $reply['pirzenum']) {
            $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
                'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
                't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
                'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
                'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
            // 在 $chars 中随机取 $length 个数组元素键名
            $length = 8;
            $keys = array_rand($chars, $length);
            $sn = '';
            for ($i = 0; $i < $length; $i++) {
                // 将 $length 个数组元素连接成字符串
                $sn .= $chars[$keys[$i]];
            }

            //if (!empty($prizetype)) {
            $insert = array(
                'weid' => $_W['uniacid'],
                'rid' => $id,
                'fansID' => $fans['id'],
                'from_user' => $from_user,
                'aid' => $k,
                'name' => $res['name'],
                'description' => $res['type'],
                'award_sn' => $sn,
                'createtime' => time(),
                'status' => 1,
            );

            if ($reply['repeat'] == 2) {
                $winning = pdo_fetch("SELECT * FROM " . tablename($this->tablewinning) . " WHERE from_user = '" . $from_user . "' AND rid = " . $id . " AND aid = " . $k);
                if (empty($winning)) {
                    $result = pdo_insert($this->tablewinning, $insert);
                    if (!empty($result))
                        $winid = pdo_insertid();
                    pdo_update('laoyou_csyx_reply', array('c_draw_' . $prizetype => $reply['c_draw_' . $prizetype] + 1), array('id' => $reply['id']));
                }
                else {
                    $sn = '您已抽取过该奖品！';
                }
            } else {
                $result = pdo_insert($this->tablewinning, $insert);
                if (!empty($result))
                    $winid = pdo_insertid();
                pdo_update('laoyou_csyx_reply', array('c_draw_' . $prizetype => $reply['c_draw_' . $prizetype] + 1), array('id' => $reply['id']));
            }

            $rt = 0;
            $success = true;
        }

        //插入摇奖日志
        pdo_insert('laoyou_csyx_shake_log', array('rid' => $id, 'weid' => $_W['uniacid'], 'fans' => $fans['id'], 'winid' => (int) $winid, 'addtime' => TIMESTAMP));


        if ($fans['num'] == 0 && $addnum == 0) {
            $rt = -2;
            $success = false;
        }
        if ($fans['num'] == 0 && $addnum > 0) {
            $rt = -99;
            $success = false;
        }
        if (!$res || $pirzenum >= $reply['pirzenum']) {
            $rt = 999;
            $success = false;
        }

        echo json_encode(array('rt' => $rt, 'success' => $success, 'awardStyle' => $typename, 'awardName' => $res['name'], 'awardCode' => $sn));

        //$out = ob_get_contents();
        //记录文本日志
        //logging_run($out);
    }

    public function doWebDeleted() {
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $sql = "SELECT id FROM " . tablename('laoyou_csyx_award') . " WHERE `id`=:id";
        $row = pdo_fetch($sql, array(':id' => $id));
        if (empty($row)) {
            message('抱歉，奖品不存在或是已经被删除！', '', 'error');
        }
        if (pdo_delete('laoyou_csyx_award', array('id' => $id))) {
            message('删除奖品成功', '', 'success');
        }
    }

    public function getRand($proArr) {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset($proArr);

        return $result;
    }

    public function doMobilerank() {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $from_user = $_W['fans']['from_user'];
        $rankList = pdo_fetchall("SELECT * FROM " . tablename($this->tablerecord) . "WHERE rid = " . $id . " and abnormal=0 ORDER BY score DESC limit 50");
        $info = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_tx') . "WHERE rid = " . $id . " AND openid = '" . $from_user . "'");
        $tx = $info['tx'];
        foreach ($rankList as $k => $v) {
            $info_tx = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_tx') . "WHERE rid = " . $id . " AND openid = '" . $v['openid'] . "'");
            $rankList[$k]['tx'] = $info_tx['tx'];
            $rankList[$k]['nn'] = $info_tx['nickname'];
            if ($v['openid'] == $from_user) {
                $rank = $k + 1;
                continue;
            }
            if ($rank == null) {
                $rank = 0;
            }
        }
        echo json_encode(array('rankList' => $rankList, 'rank' => $rank));
    }

    public function doWebManage() {
        global $_GPC, $_W;
        load()->model('reply');
        $pindex = max(1, intval($_GPC['page']));
        $psize = 20;
        $sql = "uniacid = :weid AND `module` = :module";
        $params = array();
        $params[':weid'] = $_W['uniacid'];
        $params[':module'] = 'laoyou_csyx';

        if (isset($_GPC['keywords'])) {
            $sql .= ' AND `name` LIKE :keywords';
            $params[':keywords'] = "%{$_GPC['keywords']}%";
        }
        $list = reply_search($sql, $params, $pindex, $psize, $total);
        $pager = pagination($total, $pindex, $psize);
        if (!empty($list)) {
            foreach ($list as &$item) {
                $condition = "`rid`={$item['id']}";
                $item['keywords'] = reply_keywords_search($condition);
                $laoyou_csyx = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_reply') . " WHERE rid = :rid ", array(':rid' => $item['id']));
                $fans = pdo_fetchall("SELECT * FROM " . tablename('laoyou_csyx_fans') . "WHERE rid = " . $item['id']);
                $item['abnormal'] = $laoyou_csyx['abnormal'];
                $item['fansnum'] = count($fans);
                $item['starttime'] = date('Y-m-d H:i', $laoyou_csyx['starttime']);
                $endtime = $laoyou_csyx['endtime'] + 86399;
                $item['endtime'] = date('Y-m-d H:i', $endtime);
                $nowtime = time();
                if ($laoyou_csyx['starttime'] > $nowtime) {
                    $item['status'] = '<span class="label label-red">未开始</span>';
                    $item['show'] = 1;
                } elseif ($endtime < $nowtime) {
                    $item['status'] = '<span class="label label-blue">已结束</span>';
                    $item['show'] = 0;
                }
            }
        }
        include $this->template('manage');
    }

    public function doWebAwardlist() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);

        if (empty($rid)) {
            message('抱歉，传递的参数错误！', '', 'error');
        }
        $where = '';
        $params = array(':rid' => $rid, ':weid' => $_W['uniacid']);
        if (!empty($_GPC['status'])) {
            $where.=' and a.status=:status';
            $params[':status'] = $_GPC['status'];
        }
        if (!empty($_GPC['keywords'])) {
            $where.=' and (a.award_sn like :award_sn)';
            $params[':award_sn'] = "%{$_GPC['keywords']}%";
        }

        $total = pdo_fetchcolumn("SELECT count(a.id) FROM " . tablename('laoyou_csyx_winning') . " a left join " . tablename('laoyou_csyx_fans') . " f on a.from_user=f.openid WHERE a.rid = :rid and a.weid=:weid " . $where . "", $params);
        $pindex = max(1, intval($_GPC['page']));
        $psize = 12;
        $pager = pagination($total, $pindex, $psize);
        $start = ($pindex - 1) * $psize;
        $limit .= " LIMIT {$start},{$psize}";
        //$list = pdo_fetchall("SELECT a.* FROM " . tablename('laoyou_csyx_winning') . " a left join " . tablename('laoyou_csyx_fans') . " f on a.from_user=f.openid WHERE a.rid = :rid and a.weid=:weid  " . $where . " ORDER BY a.id DESC " . $limit, $params);

        $list = pdo_fetchall("SELECT * FROM " . tablename('laoyou_csyx_winning') . " WHERE rid = " . $rid . " AND weid = " . $_W['uniacid'] . " ORDER BY id DESC " . $limit, $params);

        //一些参数的显示
        //$num1 = pdo_fetchcolumn("SELECT sum(total) FROM " . tablename('laoyou_csyx_award') . " WHERE rid = :rid", array(':rid' => $rid));
        $num2 = pdo_fetchcolumn("SELECT count(id) FROM " . tablename('laoyou_csyx_winning') . " WHERE rid = :rid and status=1", array(':rid' => $rid));
        $num3 = pdo_fetchcolumn("SELECT count(id) FROM " . tablename('laoyou_csyx_winning') . " WHERE rid = :rid and status=2", array(':rid' => $rid));

        include $this->template('awardlist');
    }

    public function doWebDownload() {
        require_once 'download.php';
    }

    public function doWebSetstatus() {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $status = intval($_GPC['status']);
        if (empty($id)) {
            message('抱歉，传递的参数错误！', '', 'error');
        }
        $p = array('status' => $status);
        if ($status == 2) {
            $p['consumetime'] = TIMESTAMP;
        }
        $temp = pdo_update('laoyou_csyx_winning', $p, array('id' => $id, 'weid' => $_W['uniacid']));
        if ($temp == false) {
            message('抱歉，刚才操作数据失败！', '', 'error');
        } else {
            message('状态设置成功！', '', 'refresh');
        }
    }

    public function doWebGetphone() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);
        $fans = $_GPC['fans'];
        $tel = pdo_fetchcolumn("SELECT tel FROM " . tablename('laoyou_csyx_fans') . " WHERE rid = " . $rid . " and  from_user='" . $fans . "'");
        if ($tel == false) {
            echo '没有登记';
        } else {
            echo $tel;
        }
    }

    public function doMobilesubmit() {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $reply = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_reply') . "WHERE rid = " . $id);
        $from_user = $_W['fans']['from_user'];
        $name = $_GPC['name'];
        $tel = $_GPC['tel'];
        $address = $_GPC['address'];
        $sn = $_GPC['sn'];
        $type = $_GPC['type'];

        if ($type == '一等奖') {
            $k = 1;
        }if ($type == '二等奖') {
            $k = 2;
        }if ($type == '三等奖') {
            $k = 3;
        }if ($type == '四等奖') {
            $k = 4;
        }if ($type == '五等奖') {
            $k = 5;
        }if ($type == '六等奖') {
            $k = 6;
        }


        $data['username'] = $name;
        $data['tel'] = $tel;
        $data['address'] = $address;

        if ($reply['repeat'] == 2) {
            $winning = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_winning') . " WHERE from_user = '" . $from_user . "' AND rid = " . $id . " AND aid = " . $k);
            if ($winning['username'] == null) {
                pdo_update('laoyou_csyx_winning', $data, array('rid' => $id, 'weid' => $_W['uniacid'], 'from_user' => $from_user, 'aid' => $k));
                $ok = 1;
            } else {
                $ok = 2;
            }
        } else {
            pdo_update('laoyou_csyx_winning', $data, array('rid' => $id, 'weid' => $_W['uniacid'], 'award_sn' => $sn));
            $ok = 1;
        }

        echo json_encode(array('ok' => $ok));
    }

    public function doMobiledosubmit() {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $reply = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_reply') . "WHERE rid = " . $id);
        $from_user = $_W['fans']['from_user'];
        $name = $_GPC['name'];
        $tel = $_GPC['tel'];
        $address = $_GPC['address'];
        $wid = $_GPC['wid'];

        $data['username'] = $name;
        $data['tel'] = $tel;
        $data['address'] = $address;

        $winning = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_winning') . " WHERE id = '" . $wid . "' AND rid = " . $id);
        if ($winning['username'] == null) {
            pdo_update('laoyou_csyx_winning', $data, array('rid' => $id, 'weid' => $_W['uniacid'], 'id' => $wid));
            $ok = 1;
        } else {
            $ok = 2;
        }


        echo json_encode(array('ok' => $ok));
    }

    public function doWebDelete() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);
        $rule = pdo_fetch("SELECT id, module FROM " . tablename('rule') . " WHERE id = :id and uniacid=:weid", array(':id' => $rid, ':weid' => $_W['uniacid']));
        if (empty($rule)) {
            message('抱歉，要修改的规则不存在或是已经被删除！');
        }
        if (pdo_delete('rule', array('id' => $rid))) {
            pdo_delete('rule_keyword', array('rid' => $rid));
            //删除统计相关数据
            pdo_delete('stat_rule', array('rid' => $rid));
            pdo_delete('stat_keyword', array('rid' => $rid));
            //调用模块中的删除
            $module = WeUtility::createModule($rule['module']);
            if (method_exists($module, 'ruleDeleted')) {
                $module->ruleDeleted($rid);
            }
        }


        message('规则操作成功！', referer(), 'success');
    }

    public function doWebDeleteAll() {
        global $_GPC, $_W;
        foreach ($_GPC['idArr'] as $k => $rid) {
            $rid = intval($rid);
            if ($rid == 0)
                continue;
            $rule = pdo_fetch("SELECT id, module FROM " . tablename('rule') . " WHERE id = :id and uniacid=:weid", array(':id' => $rid, ':weid' => $_W['uniacid']));
            if (empty($rule)) {
                $this->message('抱歉，要修改的规则不存在或是已经被删除！');
            }
            if (pdo_delete('rule', array('id' => $rid))) {
                pdo_delete('rule_keyword', array('rid' => $rid));
                //删除统计相关数据
                pdo_delete('stat_rule', array('rid' => $rid));
                pdo_delete('stat_keyword', array('rid' => $rid));
                //调用模块中的删除
                $module = WeUtility::createModule($rule['module']);
                if (method_exists($module, 'ruleDeleted')) {
                    $module->ruleDeleted($rid);
                }
            }
        }
        message('规则操作成功！', '', 0);
        //echo json_encode(array('errno'=>0));
    }

    public function doWebDeletea() {
        global $_GPC, $_W;
        foreach ($_GPC['idArr'] as $k => $rid) {
            $rid = intval($rid);
            if ($rid == 0)
                continue;
            $rule = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_winning') . " WHERE id = :id and weid=:weid", array(':id' => $rid, ':weid' => $_W['uniacid']));
            if (empty($rule)) {
                $this->message('抱歉，要修改的规则不存在或是已经被删除！');
            } else {
                pdo_delete('laoyou_csyx_winning', array('id' => $rid));
            }
        }
        message('规则操作成功！', '', 0);
        //echo json_encode(array('errno'=>0));
    }

    public function doWebFansnum() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);

        if (empty($rid)) {
            message('抱歉，传递的参数错误！', '', 'error');
        }
        $total = pdo_fetchcolumn("SELECT count(id) FROM " . tablename('laoyou_csyx_fans') . " WHERE rid = " . $rid . " and weid=" . $_W['uniacid']);
        $pindex = max(1, intval($_GPC['page']));
        $psize = 12;
        $pager = pagination($total, $pindex, $psize);
        $start = ($pindex - 1) * $psize;
        $limit .= " LIMIT {$start},{$psize}";
        //$list = pdo_fetchall("SELECT a.* FROM " . tablename('laoyou_csyx_winning') . " a left join " . tablename('laoyou_csyx_fans') . " f on a.from_user=f.openid WHERE a.rid = :rid and a.weid=:weid  " . $where . " ORDER BY a.id DESC " . $limit, $params);

        $list = pdo_fetchall("SELECT * FROM " . tablename('laoyou_csyx_fans') . " WHERE rid = " . $rid . " AND weid = " . $_W['uniacid'] . " ORDER BY id DESC " . $limit);
        $fans = pdo_fetchall("SELECT * FROM " . tablename($this->tablefans) . "WHERE rid = " . $rid);

        //一些参数的显示
        //$num1 = pdo_fetchcolumn("SELECT sum(total) FROM " . tablename('laoyou_csyx_award') . " WHERE rid = :rid", array(':rid' => $rid));
        $num = count($fans);


        include $this->template('fansnum');
    }

    public function doWebDeleteaa() {
        global $_GPC, $_W;
        foreach ($_GPC['idArr'] as $k => $rid) {
            $rid = intval($rid);
            if ($rid == 0)
                continue;
            $rule = pdo_fetch("SELECT * FROM " . tablename('laoyou_csyx_fans') . " WHERE id = :id and weid=:weid", array(':id' => $rid, ':weid' => $_W['uniacid']));
            if (empty($rule)) {
                $this->message('抱歉，要修改的规则不存在或是已经被删除！');
            } else {
                pdo_delete('laoyou_csyx_fans', array('id' => $rid));
                pdo_delete('laoyou_csyx_record', array('rid' => $rule['rid'], 'openid' => $rule['openid']));
                pdo_delete('laoyou_csyx_winning', array('rid' => $rule['rid'], 'from_user' => $rule['openid']));
                pdo_delete('laoyou_csyx_tx', array('rid' => $rule['rid'], 'openid' => $rule['openid']));
            }
        }
        message('规则操作成功！', '', 0);
        //echo json_encode(array('errno'=>0));
    }

    public function doWebData() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);
        if (empty($rid)) {
            message('抱歉，传递的参数错误！', '', 'error');
        }
        $huodong = pdo_fetch("select * from " . tablename('laoyou_csyx_reply') . " where rid=$rid limit 1");

        $starttime = $_GPC['time']['start'] ? strtotime($_GPC['time']['start']) : strtotime(date('Y-m-d', strtotime("-6day")));
        $endtime = $_GPC['time']['start'] ? strtotime($_GPC['time']['end']) : TIMESTAMP;

        $condition = "WHERE rid=$rid and weid=$_W[uniacid] and addtime between $starttime and $endtime";
        $data_join = pdo_fetchall("SELECT COUNT(*) AS `total`,FROM_UNIXTIME(addtime,'%Y%m%d') as `date` FROM " . tablename('laoyou_csyx_fans') . " $condition GROUP BY `date`", array(), 'date');
        $data_play = pdo_fetchall("SELECT COUNT(*) AS `total`,FROM_UNIXTIME(addtime,'%Y%m%d') as `date` FROM " . tablename('laoyou_csyx_play_log') . " $condition GROUP BY `date`", array(), 'date');
        $data_shake = pdo_fetchall("SELECT COUNT(*) AS `total`,FROM_UNIXTIME(addtime,'%Y%m%d') as `date` FROM " . tablename('laoyou_csyx_shake_log') . " $condition GROUP BY `date`", array(), 'date');
        $data_prize = pdo_fetchall("SELECT COUNT(*) AS `total`,FROM_UNIXTIME(addtime,'%Y%m%d') as `date` FROM " . tablename('laoyou_csyx_shake_log') . " $condition and winid<>0 GROUP BY `date`", array(), 'date');


        $sdate = date('Ymd', $starttime);
        $edate = date('Ymd', $endtime);
        $condition = "WHERE rid=$rid and weid=$_W[uniacid] and addtime between $sdate and $edate";
        $data_share = pdo_fetchall("SELECT COUNT(*) AS `total`,addtime as `date` FROM " . tablename('laoyou_csyx_share') . " $condition GROUP BY `date`", array(), 'date');

        for ($i = $starttime; $i <= $endtime; $i+=86400) {
            $date = date('Ymd', $i);
            $list[$date]['time'] = $i;
            $list[$date]['join'] = $data_join[$date]['total'] ? (int) $data_join[$date]['total'] : 0;
            $list[$date]['play'] = $data_play[$date]['total'] ? (int) $data_play[$date]['total'] : 0;
            $list[$date]['shake'] = $data_shake[$date]['total'] ? (int) $data_shake[$date]['total'] : 0;
            $list[$date]['prize'] = $data_prize[$date]['total'] ? (int) $data_prize[$date]['total'] : 0;
            $list[$date]['share'] = $data_share[$date]['total'] ? (int) $data_share[$date]['total'] : 0;
        }
        $list = array_reverse($list, true);

        include $this->template('data');
    }

    public function doWebAbnormalList() {
        global $_W, $_GPC;

        $where = $this->getAbnormalListWhere();
        $total = pdo_fetchcolumn("SELECT count(a.id) FROM " . tablename('laoyou_csyx_record') . " a " . " left join " . tablename("laoyou_csyx_tx") . " t on  a.openid=t.openid and a.weid=t.weid and a.rid=t.rid WHERE {$where} a.rid ={$_GPC['rid']} and a.weid={$_W['uniacid']}");
        $pindex = max(1, intval($_GPC['page']));
        $psize = 12;
        $pager = pagination($total, $pindex, $psize);
        $start = ($pindex - 1) * $psize;
        $limit .= " LIMIT {$start},{$psize}";
        $sql = "SELECT a.id,a.openid,a.score,a.edittime,a.abnormal,t.nickname FROM " . tablename('laoyou_csyx_record') . " a " . " left join " . tablename("laoyou_csyx_tx") . " t on a.openid=t.openid and a.weid=t.weid and a.rid=t.rid WHERE {$where} a.rid ={$_GPC['rid']} and a.weid={$_W['uniacid']} order by a.edittime desc  $limit";
        $abnormalData = pdo_fetchall($sql);
        include $this->template('abnormalList');
    }

    private function getAbnormalListWhere() {
        global  $_W,$_GPC;

        $_GPC['openid'] = trim($_GPC['openid']);
        $_GPC['nickname'] = trim($_GPC['nickname']);
        
        
        
        
        if (!empty($_GPC['openid'])) {
            $where = " a.openid like '%{$_GPC['openid']}%' ";
        }
        if (!empty($_GPC['nickname'])) {
            if (!empty($where)) {
                $where.="and t.nickname like '%{$_GPC['nickname']}%'";
            } else {
                $where = "t.nickname like  '%{$_GPC['nickname']}%'";
            }
        }
        if (!empty($_GPC['edittime'])) {
            $begin = strtotime($_GPC['edittime']['start']);
            $end = strtotime($_GPC['edittime']['end']);
            $_GPC['edittime']['start'] = $begin;
            $_GPC['edittime']['end'] = $end;
            if (!empty($where)) {
                if ($end != 0) {
                    $where.=" and a.edittime between {$begin} and {$end} ";
                }
            } else {
                if ($end != 0) {
                    $where = "a.edittime between {$begin} and {$end} ";
                }
            }
        }


        $_GPC['min'] = trim($_GPC['min']);
        $_GPC['max'] = trim($_GPC['max']);

        //没有上限
        if (!empty($_GPC['min']) && empty($_GPC['max'])) {
            if (!empty($where)) {
                $where.= " and a.score > {$_GPC['min']} ";
            } else {
                $where = " a.score > {$_GPC['min']} ";
            }
        }

        //没有下限
        if (empty($_GPC['min']) && !empty($_GPC['max'])) {
            if (!empty($where)) {
                $where.=" and a.score < {$_GPC['max']} ";
            } else {
                $where = " a.score < {$_GPC['max']} ";
            }
        }

        //上限和下限都有
        if (!empty($_GPC['min']) && !empty($_GPC['max'])) {
            if (!empty($where)) {
                $where.=" and a.score between {$_GPC['min']} and {$_GPC['max']} ";
            } else {
                $where = " a.score between {$_GPC['min']} and {$_GPC['max']}";
            }
        }

        if ($_GPC['abnormal'] == "0" || $_GPC['abnormal'] == '1') {
            if (!empty($where)) {
                $where.=" and a.abnormal={$_GPC['abnormal']}";
            } else {
                $where = " a.abnormal={$_GPC['abnormal']}";
            }
        }
        
        $abnormalScore=  pdo_fetchcolumn("select abnormal from ".tablename("laoyou_csyx_reply")." where weid={$_W['uniacid']} and rid={$_GPC['rid']}");
        if($abnormalScore>0){
            if(!empty($where)){
                $where.=" and score > {$abnormalScore}";
            }else{
                $where = " score > {$abnormalScore}";
            }
        }
        
        if (!empty($where)) {
            $where.=" and ";
        }
        return $where;
    }

    //把分数记录设置为异常
    public function doWebAbnormal() {
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $rid = intval($_GPC['rid']);
        $sql = "update " . tablename("laoyou_csyx_record") . " set abnormal=1 where id={$id} and weid={$_W['uniacid']} and rid={$rid}";
        if (pdo_query($sql)) {
            die("1");
        } else {
            die("0");
        }
    }

    //把分数记录设置为正常
    public function doWebNormal() {
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $rid = intval($_GPC['rid']);
        $sql = "update " . tablename("laoyou_csyx_record") . " set abnormal=0 where id={$id} and weid={$_W['uniacid']} and rid={$rid}";
        if (pdo_query($sql)) {
            die("1");
        } else {
            die("0");
        }
    }

    //批量把分数记录设置为异常
    public function doWebMultiAbnormal() {
        global $_W, $_GPC;
        $ids = $_GPC['ids'];
        $ids = $this->defense($ids);
        $sql = "update " . tablename("laoyou_csyx_record") . " set abnormal=1 where weid={$_W['uniacid']} and rid={$_GPC['rid']} and id in ({$ids})";
        if (pdo_query($sql)) {
            die('1');
        } else {
            die('0');
        }
    }

    //批量把分数记录设置为正常
    public function doWebMultiNormal() {
        global $_W, $_GPC;
        $ids = $_GPC['ids'];
        $ids = $this->defense($ids);
        $sql = "update " . tablename("laoyou_csyx_record") . " set abnormal=0 where weid={$_W['uniacid']} and rid={$_GPC['rid']} and id in ({$ids})";
        if (pdo_query($sql)) {
            die('1');
        } else {
            die('0');
        }
    }

    public function doWebAbnormalCustomerList() {
        global $_W, $_GPC;

        $where = $this->getBanCustomerListWhere();
        $rid = intval($_GPC['rid']);
        $sql = "select count(c.id) from "
                . tablename("laoyou_csyx_abnormal_customer") . " c left join "
                . tablename("laoyou_csyx_tx")
                . " t on c.openid=t.openid and c.weid=t.weid and c.rid=t.rid where {$where} c.weid={$_W['uniacid']} and c.rid={$rid}";
        $total = pdo_fetchcolumn($sql);
        $pindex = max(1, intval($_GPC['page']));
        $psize = 12;
        $pager = pagination($total, $pindex, $psize);
        $start = ($pindex - 1) * $psize;
        $limit .= " LIMIT {$start},{$psize}";

        $sql = "select c.id,c.openid,c.first_time,c.last_time,c.ban,t.nickname from "
                . tablename("laoyou_csyx_abnormal_customer") . " c left join "
                . tablename("laoyou_csyx_tx")
                . " t on c.openid=t.openid and c.weid=t.weid and c.rid=t.rid where {$where} c.weid={$_W['uniacid']} and c.rid={$rid} order by c.id desc $limit";
        $abnormalCustomerData = pdo_fetchall($sql);
        for ($i = 0; $i < count($abnormalCustomerData); $i++) {
            $abnormalScore=  pdo_fetchcolumn("select abnormal from ".tablename("laoyou_csyx_reply")." where weid={$_W['uniacid']} and rid={$_GPC['rid']}");
            $sql = "select count(a.id) from " . tablename("laoyou_csyx_play_log") . " a inner join " . tablename("laoyou_csyx_fans") . " b on a.fans=b.id where b.openid='{$abnormalCustomerData[$i]['openid']}' and a.weid={$_W['uniacid']} and a.rid={$rid} and a.score > {$abnormalScore}";
            $abnormalCustomerData[$i]['times'] = pdo_fetchcolumn($sql);
        }

        include $this->template("abnormalCustomerList");
    }

    //获取异常用户的搜索条件
    private function getBanCustomerListWhere() {
        global $_W, $_GPC;
        $where = "";
        $_GPC['openid'] = trim($_GPC['openid']);
        $_GPC['nickname'] = trim($_GPC['nickname']);
        if (!empty($_GPC['openid'])) {
            $where = " c.openid like '%{$_GPC['openid']}%' ";
        }
        if (!empty($_GPC['nickname'])) {
            if (!empty($where)) {
                $where.="and t.nickname like '%{$_GPC['nickname']}%'";
            } else {
                $where = "t.nickname like  '%{$_GPC['nickname']}%'";
            }
        }
        if (!empty($_GPC['firstTime'])) {
            $begin = strtotime($_GPC['firstTime']['start']);
            $end = strtotime($_GPC['firstTime']['end']);
            $_GPC['firstTime']['start'] = $begin;
            $_GPC['firstTime']['end'] = $end;
            if (!empty($where)) {
                if ($end != 0) {
                    $where.=" and c.first_time between {$begin} and {$end} ";
                }
            } else {
                if ($end != 0) {
                    $where = "c.first_time between {$begin} and {$end} ";
                }
            }
        }
        if (!empty($_GPC['lastTime'])) {
            $begin = strtotime($_GPC['lastTime']['start']);
            $end = strtotime($_GPC['lastTime']['end']);
            $_GPC['lastTime']['start'] = $begin;
            $_GPC['lastTime']['end'] = $end;
            if (!empty($where)) {
                if ($end != 0) {
                    $where.=" and c.last_time between {$begin} and {$end} ";
                }
            } else {
                if ($end != 0) {
                    $where = " c.last_time between {$begin} and {$end} ";
                }
            }
        }
        if ($_GPC['ban'] == "0" || $_GPC['ban'] == "1") {
            if (!empty($where)) {
                $where.=" and c.ban={$_GPC['ban']}";
            } else {
                $where = " c.ban={$_GPC['ban']}";
            }
        }
        if (!empty($where)) {
            $where.=" and ";
        }
        return $where;
    }

    //封杀用户
    public function doWebBanCustomer() {
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $rid = intval($_GPC['rid']);
        $sql = "update " . tablename("laoyou_csyx_abnormal_customer") . " set ban=1 where id={$id} and weid={$_W['uniacid']} and rid={$rid}";
        if (pdo_query($sql)) {
            die("1");
        } else {
            die("0");
        }
    }

    //解封用户
    public function doWebRelieveCustomer() {
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $rid = intval($_GPC['rid']);
        $sql = "update " . tablename("laoyou_csyx_abnormal_customer") . " set ban=0 where id={$id} and weid={$_W['uniacid']} and rid={$rid}";
        if (pdo_query($sql)) {
            die("1");
        } else {
            die("0");
        }
    }

    public function doWebMultiBanCustomer() {
        global $_W, $_GPC;
        $ids = $_GPC['ids'];
        $ids = $this->defense($ids);
        $sql = "update " . tablename("laoyou_csyx_abnormal_customer") . " set ban=1 where weid={$_W['uniacid']} and rid={$_GPC['rid']} and id in ({$ids})";
        if (pdo_query($sql)) {
            die('1');
        } else {
            die('0');
        }
    }

    public function doWebMultiRelieveCustomer() {
        global $_W, $_GPC;
        $ids = $_GPC['ids'];
        $ids = $this->defense($ids);
        $sql = "update " . tablename("laoyou_csyx_abnormal_customer") . " set ban=0 where weid={$_W['uniacid']} and rid={$_GPC['rid']} and id in ({$ids})";
        if (pdo_query($sql)) {
            die('1');
        } else {
            die('0');
        }
    }

    private function defense($ids) {
        $ids = explode(',', $ids);
        for ($i = 0; $i < count($ids); $i++) {
            $ids[$i] = intval($ids[$i]);
        }
        return implode(',', $ids);
    }

}

?>